package hu.myai.triggers.bullish;

import hu.myai.api.tick.AbstractTickProvider;
import hu.myai.api.triggers.AbstractTrigger;
import hu.myai.indicators.LowerBollingerIndicator;
import hu.myai.indicators.tick.TickPositionChangeIndicator;
import hu.myai.indicators.tick.TickIndicator;
import hu.myai.indicators.tick.TickVolumeChangeIndicator;
import hu.myai.model.IndicatorVO;
import hu.myai.model.TriggerVO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The candle not goes thru the low bollinger and starts to go the the upper
 * bollinger TODO test with real data
 * 
 * @author bozbalint
 * 
 * */

public class TurningAtLowBollingerTrigger extends AbstractTrigger {

    Double firstPositionValue;
    Double firstBollingerValue;
    Double firstVolumeValue;
    Double firstTickValue;

    /**
     * The object used when logging debug,errors,warnings and info.
     * */
    private final Logger log = LoggerFactory.getLogger(this.getClass());


    private String positionID;
    private String volumeID;
    private String tickID;

    public TurningAtLowBollingerTrigger(String name, AbstractTickProvider tick) {
        super(name, tick);
        positionID = register(new TickPositionChangeIndicator());
        volumeID = register(new TickVolumeChangeIndicator());
        tickID = register(new TickIndicator(TickIndicator.CLOSE));
    }

    private String lowBollingerID;

    public void setLowerBollingerIndicatorParameter(double parameter) {
        lowBollingerID = register(new LowerBollingerIndicator(parameter));
    }

    @Override
    protected TriggerVO triggerCalculation() {

        IndicatorVO positionIndicator = indicatorMap.get(positionID);
        IndicatorVO bollingerIndicator = indicatorMap.get(lowBollingerID);
        IndicatorVO volumeIndicator = indicatorMap.get(volumeID);
        IndicatorVO tickIndicator = indicatorMap.get(tickID);

        // ignore calculation if no indicator value
        if (positionIndicator == null || bollingerIndicator == null || volumeIndicator == null || tickIndicator == null) {
            return null;
        }

        // the logic: lower candle high volume, the close is at
        if (positionIndicator.getValue() < 1.0 && volumeIndicator.getValue() > 1.7
                && isInPct(bollingerIndicator.getValue() / tickIndicator.getValue(), 3)) {

            
            TriggerVO trigger = new TriggerVO();
            trigger.setTick(lastTick);
            trigger.setRisk(20);
            trigger.setTradeType(TriggerVO.BUY_ONMARKET);

            log.debug(trigger.toString());
            return trigger;
        }
        return null;
    }

    private boolean isInPct(double value, int limit) {
        return value < (1.0 + (limit / 100.0)) && value > (1.0 - (limit / 100.0));
    }
}
